var express = require('express');
var router = express.Router();
var fs=require('fs');
/* GET home page. */
var mongoose = require('mongoose');    //引用mongoose模块
var db = mongoose.createConnection('mongodb://127.0.0.1:27017/nodetest');
db.on('error',console.error.bind(console,'连接错误:'));
var userSchema = new mongoose.Schema({ //推荐schema的名字，用object名字后缀Schema
  name: String,
  pass:String
});//admins表数据结构
var talkSchema = new mongoose.Schema({
    aid:String,
    title:String,
    date:{type:Date,default:Date.now()},
    content:String
});
var regerSchema = new mongoose.Schema({
    name:String,
    password:String,
    nickname:String,
    sex:String,
    photo:String,
   // email:String,
    qq:String,
   // url:String,
    date:{type:Date,default:Date.now()},
    isvisit:{type:Number, default:0},//0允许用户访问，1禁止用户访问
    isonline:{type:Number, default:0},//0用户离线,1用户在线
    talk:[talkSchema]
});//注册用户表结构

var articleSchema= new mongoose.Schema({
    title:String,
    key:String,
    desc:String,
    date:String,
    img:String,
    look:Number,
    profile:String,
    columnid:String,
    columnname:String,
    content:String
});//文章表结构

var columnSchema=new mongoose.Schema({
    name:String,
    key:String,
    desc:String,
    pid:Number,
    fid:{type:String,default:"0"},
    article:[articleSchema]
});//栏目表结构

/*
*
* 表结构结束
*
* */










/***
 *
 *
 *前台操作开始************************************************************************************************************
 *
 *
 *           ***/



var PW = require("png-word");
var pw = PW(PW.GRAY);

router.get('/refresh',function(req,res,next){
    var charactors="ab1cd2ef3gh4ij5kl6mn7opq8rst9uvw0xyz";
    var value='',i;
    for(var j=1;j<=4;j++){
        i = parseInt(35*Math.random());
	    value = value + charactors.charAt(i);
    }
    req.session.validat=value;

   console.log(value);
    pw.createPNG(value,function(pngnum){
        res.send(pngnum);
    })

});//验证码获取




router.get('/', function(req, res, next) {
    var Column=db.model('column', columnSchema,'column');
    var nav,articlelist;
    Column.find().sort({pid: 1}).exec('find',function(err,doc){

            if(err){
                res.send(err);
            }else{
                nav=doc;
                Column.find(function(err,result){
                    if(err){
                        res.send(err);
                    }else{

                        var list=[];
                        for(var i=0;i<result.length;i++){
                            if(result[i].article.length>0){
                                for(var t=0;t<result[i].article.length;t++){
                                    list.unshift(result[i].article[t]);//按照文档的时间顺序，最后的添加的数组的最前面
                                }
                            }
                        }//读取所有栏目子文档
                        var pagelist=10;//每页显示多少条
                        var nowpage;//当前页
                        var count=list.length;//总共多少数据
                        var pagecount=Math.ceil(count/pagelist);//总页数
                        if(req.query.nowpage){
                            if(req.query.nowpage>pagecount){
                                nowpage=pagecount-1;//超出尾页
                            }else{
                                nowpage=req.query.nowpage;//否则就赋值当前页
                            }

                        }else{
                            nowpage=0;
                        }

                        list=list.slice(nowpage*pagelist,pagelist+nowpage*pagelist);//数组分页输出
                        articlelist=list;
                        res.render('index',{title:'神话的个人博客 | 前端之光—分享网站前端开发的点点滴滴^o^',nav:doc,articlelist:articlelist,nownav:'首页'});
                    }

                });
            }

    });




});//首页



router.get('/list/:id/:p?', function(req, res,next) {
   var id=req.params.id;
    var p=req.params.p;
    var Column=db.model('column', columnSchema,'column');
    var nav,articlelist;
    Column.find().sort({pid: 1}).exec('find',function(err,doc){

        if(err){
            res.send(err);
        }else{
            nav=doc;
            Column.findOne({_id:id},function(err,result){
                if(err){
                    res.send(err);
                }else{
                   // console.log(result);
                    var list=[];

                        if(result.article.length>0){
                            for(var t=0;t<result.article.length;t++){
                                list.unshift(result.article[t]);//按照文档的时间顺序，最后的添加的数组的最前面
                            }
                        }

                    var pagelist=10;//每页显示多少条
                    var nowpage=p;//当前页
                    var count=list.length;//总共多少数据
                    var pagecount=Math.ceil(count/pagelist);//总页数
                    if(nowpage){
                        if(req.query.nowpage>pagecount){
                            nowpage=pagecount-1;//超出尾页
                        }else{
                            nowpage=p;//否则就赋值当前页
                        }

                    }else{
                        nowpage=0;
                    }
                    var navstring='';//导航条HTML
                    if(pagecount>0){
                        var url="/list/"+result._id+"/";//导航URL
                        for(var i=0;i<pagecount;i++){
                            if(nowpage==i){
                                navstring+='<a href='+url+i+' class="now-page">'+(i+1)+'</a>';
                            }else{
                                navstring+='<a href='+url+i+'>'+(i+1)+'</a>';
                            }

                        }
                        navstring="<a href="+url+"0>首页</a>"+navstring+"<a href="+url+(pagecount-1)+">尾页</a>";
                    }


                    list=list.slice(nowpage*pagelist,pagelist+nowpage*pagelist);//数组分页输出
                    articlelist=list;
                    res.render('page/articlelist',{title:result.name+'_神话的个人博客 | 前端之光—分享网站前端开发的点点滴滴^o^',
                        nav:doc,articlelist:articlelist,navpage:navstring,nownav:result.name});
                }

            });
        }

    });


});//文章列表



router.get('/article/:id', function(req, res,next) {
    var id=req.params.id;
    var Column=db.model('column', columnSchema,'column');
    Column.find().sort({pid: 1}).exec('find',function(err,doc){

        if(err){
            res.send(err);
        }else{

            Column.find(function(err,result){
                if(err){
                    res.send(err);
                }else{

                    var list=[];
                    var articlelist=[];
                    for(var i=0;i<result.length;i++){
                        if(result[i].article.length>0){
                            for(var t=0;t<result[i].article.length;t++){
                                list.unshift(result[i].article[t]);//按照文档的时间顺序，最后的添加的数组的最前面
                            }
                        }
                    }//读取所有栏目子文档
                    for(var n=0;n<list.length;n++){
                        if(list[n]._id==id){
                            articlelist.push(list[n]);
                            break;
                        }
                    }//取出符合ID的文档

                    res.render('page/article',{title:articlelist[0].title+'_神话的个人博客 | 前端之光—分享网站前端开发的点点滴滴^o^',
                        nav:doc,articlelist:articlelist,nownav:articlelist[0].columnname,articleid:id});
                }

            });
        }

    });


});//文章内容






router.post('/talkenter',function(req,res,next){
      if(!req.session.login){
          res.json({success:0,text:"请先登录在评论!"});
          return false;
      }
      var talk={title:req.body.title,content:req.body.content,id:req.body.id,code:req.body.code};
      if(talk.title==''||talk.content==''||talk.id==''||talk.code==''){
          res.json({success:0,text:"请填写验证码或评论内容！"});
          return false;
      }
     if(talk.code!=req.session.validat){
         res.json({success:0,text:"请输入正确的验证码!"});
         console.log(talk.code);
         console.log(req.session.validat);
         return false;
     }
     var user=db.model('user', regerSchema,'user');
     user.findOne({name:req.session.name},function(err,doc){
          if(err){
              res.send(err);
          }else{
              doc.talk.push({aid:talk.id,title:talk.title,content:talk.content});
              doc.save(function(err){
                  if(err){
                      res.send(err);
                  }else{
                      res.json({success:1})
                  }
              })
          }
     })
});//用户评论提交






router.post('/talklist',function(req,res,next){
      var talk=db.model('user', regerSchema,'user');
      talk.find(function(err,doc){
          if(err){
              res.send(err);
          }else{
              var list=[];
              for(var i=0;i<doc.length;i++){
                  if(doc[i].talk.length>0){
                      for(var t=0;t<doc[i].talk.length;t++){
                          if(doc[i].talk[t].aid==req.body.id){
                              var b={name:doc[i].nickname,img:doc[i].photo};
                               list.push(doc[i].talk[t]);
                               list.push(b);

                          }
                      }//获取用户当前文章评论
                  }
              }//循环获取用户评论
              res.json({success:1,list:list});
          }
      })
});//文章评论拉取







router.post('/reg', function(req, res,next) {
    var user={nick:req.body.userNick,name:req.body.userName,password:req.body.userPassword,qq:req.body.userQQ,sex:req.body.userSex,photo:req.files.userImg,code:req.body.codeValue};
    console.log(user);
    if(user.nick===undefined || user.name===undefined || user.password===undefined || user.qq===undefined || user.sex===undefined || user.photo===undefined || user.code===undefined){
        res.send('注册失败，请认真仔细认真仔细认真仔细再注册^-^!!!');
    }else if (user.photo.extension!='jpg' && user.photo.extension!='png' && user.photo.extension!='gif'){
        fs.unlink('./'+user.photo.path);
        res.send('注册失败，请上传格式为gif,jpg,png的头像图片^-^!!!');
    }else if(user.photo.size>1048576){
        fs.unlink('./'+user.photo.path);
        res.send('注册失败，请上传小于1M的头像图片^-^!!!');
    }else if(req.session.validat!=user.code){
        fs.unlink('./'+user.photo.path);
        res.send('注册失败，请输入正确的验证码^-^!!!');

    }else{
        fs.renameSync('./'+user.photo.path, './public/upload/userphoto/'+user.photo.name);//重命名到新的目录里
        var Reg=db.model('user', regerSchema,'user');
        var Newuser=new Reg({
            name:user.name,
            password:user.password,
            nickname:user.nick,
            sex:user.sex,
            photo:user.photo.name,
            qq:user.qq

        });
        Newuser.save(function(err){
           if(err){
               res.send(err);
           } else{
               req.session.login=true;
               req.session.name=user.name;
               res.redirect('/');
           }
        });

    }


});//会员注册





router.post('/login', function(req, res,next) {
    var data={name:req.body.name,password:req.body.password,code:req.body.code};
    if(data.name=='' || data.password=='' || data.code=='' ){
        res.json({success:2,text:"请输入完整的用户名或密码！"});//填写表单
    }else if(req.session.validat!=data.code){
        res.json({success:2,text:'验证码错误！'});//验证码错误
    }else{
        var Nser=db.model('user', regerSchema,'user');
        Nser.count({name:data.name,password:data.password},function(err,d){
            if (d == 1) {
                Nser.find({name:data.name},function (err, result) {
                    if (err) {
                        res.send(err);
                    } else {
                        req.session.login = true;
                        req.session.name=data.name;
                        Nser.update({name:data.name},{isonline:1},function(err){
                            if(err){
                                res.send(err);
                            }else{
                                res.json({success:1});//登陆成功
                            }
                        });


                    }
                });//读取数据库

            } else {
                res.json({success:0});//登陆失败

            }

        });//匹配数据库
    }

});//会员登陆








router.post('/getuserlist', function(req, res,next) {
    var isadmin=true;
    var Nser=db.model('user', regerSchema,'user');
    if(req.session.login){
        isadmin=false;
        Nser.find({name:req.session.name},function (err, result) {
            if (err) {
                res.send(err);
            } else {
                Nser.find(function (err, doc) {
                    if (err) {
                        res.send(err);
                    } else {
                        res.json({success:0,isadmin:isadmin,user:result,userlist:doc});

                    }
                });//读取所有用户数据


            }
        });//读取登陆用户数据
    }else{
        Nser.find(function (err, doc) {
            if (err) {
                res.send(err);
            } else {
                res.json({success:0,isadmin:isadmin,userlist:doc});

            }
        });//读取所有用户数据
    }//用户未登录的时候


});//会员列表


/***
 *
 *
 *前台操作结束************************************************************************************************************
 *
 *
 *           ***/



















/***
 *
 *
 *后台操作开始************************************************************************************************************
 *
 *
 *           ***/



function checklogin(req,res,next){
     if(!req.session.user){
         res.redirect("/gaolk");
     }// 判断用户是否登陆
     next();
}//检测是否登陆


function ColumnList(){
    var list;
    var Column=db.model('column', columnSchema,'column');
    Column.find(function(err,result){
        if(err){

        }else{
            var s=[];// [{1,2,3}]
            for(var i=0;i<result.length;i++){

            }
            list=result;
        }
    });
    return list;
}//返回栏目列表


router.post('/upload',function(req,res,next){

    res.json({error:0,url:'/upload/'+req.files.imgFile.name});

});//上传图片



router.get('/gaolk',function(req,res,next){
    res.render('gaolk/index',{title:'后台管理登陆'});
}).post('/gaolk',function(req,res,next){
    var Nser=db.model('user', userSchema,'admins');
    var urequery={name:req.body.name,pass:req.body.pass};

    Nser.count(urequery,function(err,d){
        if (d == 1) {
             Nser.find(function (err, result) {
                if (err) {
                    res.send(err);
                } else {
                    req.session.user = true;
                    res.json({success:1});//ajax返回JSON数据

                }
            });//读取数据库

        } else {
                   res.json({success:0});//ajax返回JSON数据

        }

    });//匹配数据库
});//后台登陆



router.get('/mycenter',checklogin);
router.get('/mycenter',function(req,res,next){

    res.render('gaolk/center',{title:'后台管理中心'});
}); //后台首页



router.get('/mycenter/config',function(req,res,next){
    res.render('gaolk/config');
});//网站配置



router.get('/mycenter/admin',checklogin);
router.get('/mycenter/admin',function(req,res,next){
    var Nser=db.model('user', userSchema,'admins');
    Nser.find(function (err, result){
           if(err){
               res.send(err);
           }else{
               res.render('gaolk/admin',{d:0,adminlist:result});
           }
    });//账户显示

}).post('/mycenter/admin',function(req,res,next){
    var urequery={id:req.body.id,name:req.body.user,pass:req.body.pass};
    var Nser=db.model('user', userSchema,'admins');
    Nser.update({_id:urequery.id},{name:urequery.name,pass:urequery.pass},function(err){
          if(err){
              res.send(err);
          }else{
              res.render('gaolk/admin',{d:1});
          }
    }); // 更新数据
});//账户修改



router.get('/mycenter/link',function(req,res,next){
    res.render('gaolk/link');
});//友情链接列表
router.get('/mycenter/addlink',function(req,res,next){
    res.render('gaolk/addlink');
});//友情链接增加
router.get('/mycenter/dellink',function(req,res,next){
    res.render('gaolk/dellink');
});//友情链接删除
router.get('/mycenter/changelink',function(req,res,next){
    res.render('gaolk/changelink');
});//友情链接更新



router.get('/mycenter/column',checklogin);
router.get('/mycenter/column',function(req,res,next){
    var Column=db.model('column', columnSchema,'column');
    var pagelist=10;//每页显示多少条
    var nowpage;//当前页
    var count;//总共多少数据
    var query=Column.find().sort({_id: -1});//总共的数据文档
    query.count(function(err,counts){
        count=counts;
        var pagecount=Math.ceil(count/pagelist);//总页数
        if(req.query.nowpage){
            if(req.query.nowpage>pagecount){
                nowpage=pagecount-1;//超出尾页
            }else{
                nowpage=req.query.nowpage;//否则就赋值当前页
            }

        }else{
            nowpage=0;
        }
        query.skip(nowpage*pagelist).limit(pagelist).exec('find',function(err,result){
            if(err){
                res.send(err);
            }else{
                var navstring='';//导航条HTML
                var url="/mycenter/column?";//导航URL
                for(var i=0;i<pagecount;i++){
                       if(nowpage==i){
                           navstring+='<a href='+url+'nowpage='+i+' class="now">'+(i+1)+'</a>';
                       }else{
                           navstring+='<a href='+url+'nowpage='+i+'>'+(i+1)+'</a>';
                       }

                }
                navstring="<a href="+url+"nowpage=0>首页</a>"+navstring+"<a href="+url+"nowpage="+(pagecount-1)+">尾页</a>";
                res.render('gaolk/column',{columnlist:result,nav:navstring});
            }
        });
    });


});//栏目列表
router.get('/mycenter/delcolumn',checklogin);
router.get('/mycenter/delcolumn',function(req,res,next){
    var Column=db.model('column', columnSchema,'column');
    Column.remove({_id:req.query.id},function(err){
        if(err){
            res.send(err);
        }else{
            res.send('删除成功!');
           
        }
    });

});//栏目删除
router.get('/mycenter/addcolumn',checklogin);
router.get('/mycenter/addcolumn',function(req,res,next){
    var Column=db.model('column', columnSchema,'column');
    Column.find(function(err,result){
        if(err){
           res.send(err);
        }else{
            var s=[];
            for(var i=0;i<result.length;i++){
                if(result[i].fid==='0'){
                    var flag=false;
                    var childrencolumn=[];
                        childrencolumn.push(result[i]);
                    for(var t=0;t<result.length;t++){
                       if(result[t].fid==result[i]._id){

                           childrencolumn.push(result[t]);
                           flag=true;
                           //console.log(result[t]);
                       }
                    }//获取子栏目插入数组
                    if(flag==false){
                          s.push(result[i]);
                    }else{

                          s.push(childrencolumn);
                    }

                }
            }//获取父栏目插入数组

            res.render('gaolk/addcolumn',{d:0,columnlist:s});
        }
    });



}).post('/mycenter/addcolumn',function(req,res,next){
    var colquery={name:req.body.name,key:req.body.key,desc:req.body.desc,pid:req.body.pid,fid:req.body.fid};
    var Column=db.model('column', columnSchema,'column');
    var savecolumn=new Column({
        name:colquery.name,
        key:colquery.key,
        desc:colquery.desc,
        pid:colquery.pid,
        fid:colquery.fid
    });
    savecolumn.save(function (err) {
       if(err){
           res.send(err);
       }else{
           res.render('gaolk/addcolumn',{d:1});
       }
    });

});//栏目添加
router.get('/mycenter/changecolumn',checklogin);
router.get('/mycenter/changecolumn',function(req,res,next){
    var Column=db.model('column', columnSchema,'column');
    Column.find({_id:req.query.id},function(err,result){
        if(err){
            res.send(err);
        }else{
            var s=[];
            for(var i=0;i<result.length;i++){
                if(result[i].fid==='0'){

                    for(var t=0;t<result.length;t++){
                        if(result[t].fid==result[i]._id){
                            s[i]=[];
                            s[i].push(result[i]);
                            s[i].push(result[t]);
                        }else{
                            s[i]=result[i];
                        }
                    }//获取子栏目插入数组
                }
            }//获取父栏目插入数组
            res.render('gaolk/changecolumn',{d:0,columnlist:s});
        }
    });

}).post('/mycenter/changecolumn',function(req,res,next){
    var colquery={name:req.body.name,key:req.body.key,desc:req.body.desc,pid:req.body.pid,fid:req.body.fid};
    var Column=db.model('column', columnSchema,'column');

    Column.update({_id:req.body.id},colquery,function (err) {
        if(err){
            res.send(err);
        }else{
            res.render('gaolk/changecolumn',{d:1});
        }
    });

});//栏目修改



router.get('/mycenter/talk',function(req,res,next){
    res.render('gaolk/talk');
});//评论列表
router.get('/mycenter/deltalk',function(req,res,next){
    res.render('gaolk/deltalk');
});//评论删除
router.get('/mycenter/replytalk',function(req,res,next){
    res.render('gaolk/replytalk');
});//回复评论


router.get('/mycenter/user',checklogin);
router.get('/mycenter/user',function(req,res,next){
    var user=db.model('user', regerSchema,'user');
    var pagelist=10;//每页显示多少条
    var nowpage;//当前页
    var count;//总共多少数据
    var query=user.find().sort({_id: -1});//总共的数据文档
    query.count(function(err,counts){
        count=counts;
        var pagecount=Math.ceil(count/pagelist);//总页数
        if(req.query.nowpage){
            if(req.query.nowpage>pagecount){
                nowpage=pagecount-1;//超出尾页
            }else{
                nowpage=req.query.nowpage;//否则就赋值当前页
            }

        }else{
            nowpage=0;
        }
        query.skip(nowpage*pagelist).limit(pagelist).exec('find',function(err,result){
            if(err){
                res.send(err);
            }else{
                var navstring='';//导航条HTML
                var url="/mycenter/column?";//导航URL
                for(var i=0;i<pagecount;i++){
                    if(nowpage==i){
                        navstring+='<a href='+url+'nowpage='+i+' class="now">'+(i+1)+'</a>';
                    }else{
                        navstring+='<a href='+url+'nowpage='+i+'>'+(i+1)+'</a>';
                    }

                }
                navstring="<a href="+url+"nowpage=0>首页</a>"+navstring+"<a href="+url+"nowpage="+(pagecount-1)+">尾页</a>";
                res.render('gaolk/user',{userlist:result,nav:navstring});
            }
        });
    });

});//用户列表
router.get('/mycenter/deluser',checklogin);
router.get('/mycenter/deluser',function(req,res,next){
    var user=db.model('user', regerSchema,'user');
    user.remove({_id:req.query.id},function(err,doc){
        if(err){
            res.send(err);
        }else{

            res.send("删除成功！");
        }
    });

});//删除用户
router.get('/mycenter/lookuser',checklogin);
router.get('/mycenter/lookuser',function(req,res,next){
    var user=db.model('user', regerSchema,'user');
    user.find({_id:req.query.id},function(err,doc){
       if(err){
           res.send(err);
       }else{

           res.render('gaolk/lookuser',{userlist:doc});
       }
    });

});//查看用户



router.get('/mycenter/message',function(req,res,next){
    res.render('gaolk/message');
});//留言列表
router.get('/mycenter/delmessage',function(req,res,next){
    res.render('gaolk/delmessage');
});//删除留言
router.get('/mycenter/replymessage',function(req,res,next){
    res.render('gaolk/replymessage');
});//回复留言



router.get('/mycenter/addarticle',checklogin);
router.get('/mycenter/addarticle',function(req,res,next){
    var Column=db.model('column', columnSchema,'column');
    Column.find(function(err,result){
        if(err){
            res.send(err);
        }else{
            var s=[];
            for(var i=0;i<result.length;i++){
                if(result[i].fid==='0'){
                    var flag=false;
                    var childrencolumn=[];
                    childrencolumn.push(result[i]);
                    for(var t=0;t<result.length;t++){
                        if(result[t].fid==result[i]._id){

                            childrencolumn.push(result[t]);
                            flag=true;
                            //console.log(result[t]);
                        }
                    }//获取子栏目插入数组
                    if(flag==false){
                        s.push(result[i]);
                    }else{

                        s.push(childrencolumn);
                    }

                }
            }//获取父栏目插入数组
            var d=new Date();
            var time = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();
            res.render('gaolk/addarticle',{d:0,columnlist:s,time:time});
        }
    });

}).post('/mycenter/addarticle',function(req,res,next){
    var articlequery={title:req.body.title,key:req.body.key,desc:req.body.desc,date:req.body.date,
        img:req.files.img.name,look:req.body.look,profile:req.body.profile,columnid:req.body.column,columnname:'',content:req.body.content};
    var Column=db.model('column', columnSchema,'column');
    Column.findOne({_id:articlequery.columnid},null,function(err,doc){
        if(err){
            res.send(err);
        }else{

           /* if(req.files.img.size>500000){
                console.log('111');
                fs.unlink('./'+req.files.img.path);
            }*/
            articlequery.columnname=doc.name;
            doc.article.push(articlequery);//push增加数据
            doc.save(function(err){
                   if(err){
                       res.send(err);
                   }else{

                       res.render('gaolk/addarticle',{d:1});
                   }
            });//保存数据

        }
    });

});//添加文章
router.get('/mycenter/delarticle',checklogin);
router.get('/mycenter/delarticle',function(req,res,next){
    var Column=db.model('column', columnSchema,'column');
    Column.findOne({_id:req.query.fid},null,function(err,doc){
        if(err){
            res.send(err);
        }else{

            for(var i=0;i<doc.article.length;i++){
                if(doc.article[i]._id==req.query.id){
                    doc.article[i].remove();//删除成功
                }
            }
            doc.save(function(err){
                if(err){
                    res.send(err);
                }else{
                    res.send('删除文章成功!');
                }
            });//保存数据

        }
    });

});//删除文章
router.get('/mycenter/changearticle',checklogin);
router.get('/mycenter/changearticle',function(req,res,next){
    var columnlist;
    var Column=db.model('column', columnSchema,'column');
    Column.find(function(err,result){
        if(err){
            res.send(err);
        }else{
            var s=[];
            for(var i=0;i<result.length;i++){
                if(result[i].fid==='0'){
                    var flag=false;
                    var childrencolumn=[];
                    childrencolumn.push(result[i]);
                    for(var t=0;t<result.length;t++){
                        if(result[t].fid==result[i]._id){

                            childrencolumn.push(result[t]);
                            flag=true;
                            //console.log(result[t]);
                        }
                    }//获取子栏目插入数组
                    if(flag==false){
                        s.push(result[i]);
                    }else{

                        s.push(childrencolumn);
                    }

                }
            }//获取父栏目插入数组
            columnlist=s;
            Column.findOne({_id:req.query.fid},null,function(err,doc){
                if(err){
                    res.send(err);
                }else{
                    var s;
                    for(var i=0;i<doc.article.length;i++){
                        if(doc.article[i]._id==req.query.id){
                            s=doc.article[i];
                        }
                    }
                   console.log(s);
                    res.render('gaolk/changearticle',{d:0,list:s,columnlist:columnlist,columnid:req.query.fid,columnname:doc.name});

                }
            });
        }
    });


}).post("/mycenter/changearticle",function(req,res,next){
    var UpdataArticle={title:req.body.title,key:req.body.key,desc:req.body.desc,date:req.body.date,
                       img:req.body.imgurl,look:req.body.look,profile:req.body.profile,columnid:req.body.column,columnname:req.body.columnname,
                       content:req.body.content
                      };//获取要更新的数据
    var Column=db.model('column', columnSchema,'column');
    if(UpdataArticle.columnid==req.body.columnid) {
        Column.findOne({_id: req.body.column}, null, function (err, result) {
            if (err) {
                res.send(err);
            } else {
                for (var i = 0; i < result.article.length; i++) {
                    if (result.article[i]._id == req.body.id) {
                        result.article[i].title = UpdataArticle.title;
                        result.article[i].key = UpdataArticle.key;
                        result.article[i].desc = UpdataArticle.desc;
                        result.article[i].date = UpdataArticle.date;
                        result.article[i].img = UpdataArticle.img;
                        result.article[i].look = UpdataArticle.look;
                        result.article[i].columnid = UpdataArticle.columnid;
                        result.article[i].columnname = UpdataArticle.columnname;
                        result.article[i].content = UpdataArticle.content;
                        result.save(function (err) {
                            if (err) {
                                res.send(err);
                            } else {
                                res.render('gaolk/changearticle', {d: 1});
                            }
                        });
                        break;
                    }
                }//更新子文档
            }
        });
    }else{ //---文章栏目没有修改的情况
        Column.findOne({_id: req.body.columnid}, null, function (err, result) {
            if (err) {
                res.send(err);
            } else {
                for (var i = 0; i < result.article.length; i++) {
                    if (result.article[i]._id == req.body.id) {
                        result.article[i].remove();//先删除原栏目的文章
                        result.save(function (err) {
                            if (err) {
                                res.send(err);
                            } else {
                                Column.findOne({_id:UpdataArticle.columnid}, null, function (err,doc) {
                                    if (err) {
                                        res.send(err);
                                    } else {
                                        doc.article.push(UpdataArticle);//push增加数据
                                        doc.save(function(err){
                                           if(err){
                                               res.send(err);
                                           }else{
                                               res.render('gaolk/changearticle', {d: 1});
                                            }
                                        });
                                        //在更新新修改的栏目子文档
                                    }
                                });

                            }
                        });
                        break;
                    }
                }//更新子文档
            }
        });
    } //--文档栏目已经修改的情况
});//更新文章
router.get('/mycenter/article',checklogin);
router.get('/mycenter/article',function(req,res,next){
    var Column=db.model('column', columnSchema,'column');
    Column.find(function(err,result){
        if(err){
            res.send(err);
        }else{

            var list=[];
            for(var i=0;i<result.length;i++){
                if(result[i].article.length>0){
                      for(var t=0;t<result[i].article.length;t++){
                          list.unshift(result[i].article[t]);//按照文档的时间顺序，最后的添加的数组的最前面
                      }
                }
            }//读取所有栏目子文档
            var pagelist=10;//每页显示多少条
            var nowpage;//当前页
            var count=list.length;//总共多少数据
            var pagecount=Math.ceil(count/pagelist);//总页数
            if(req.query.nowpage){
                if(req.query.nowpage>pagecount){
                    nowpage=pagecount-1;//超出尾页
                }else{
                    nowpage=req.query.nowpage;//否则就赋值当前页
                }

            }else{
                nowpage=0;
            }
            var navstring='';//导航条HTML
            var url="/mycenter/article?";//导航URL
            for(var i=0;i<pagecount;i++){
                if(nowpage==i){
                    navstring+='<a href='+url+'nowpage='+i+' class="now">'+(i+1)+'</a>';
                }else{
                    navstring+='<a href='+url+'nowpage='+i+'>'+(i+1)+'</a>';
                }

            }
            navstring="<a href="+url+"nowpage=0>首页</a>"+navstring+"<a href="+url+"nowpage="+(pagecount-1)+">尾页</a>";
            list=list.slice(nowpage*pagelist,pagelist+nowpage*pagelist);//数组分页输出
            res.render('gaolk/article',{articlelist:list,nav:navstring});
        }

    });

});//管理文章




/***
 *
 *
 * 后台操作结束***********************************************************************************************************
 *
 *
 *           ***/




module.exports = router;



